package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Product;
import org.shiro.demo.entity.ProductDetail;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IProductDetailService;
import org.shiro.demo.service.IProductService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/productDetail")
public class ProductDetailController {
	@Resource(name = "productDetailService")
	private IProductDetailService productDetailService;
	@Resource(name = "productService")
	private IProductService productService;

	@Resource(name = "baseService")
	private IBaseService baseService;

	/**
	 * 拿到某个产品的产品详情
	 * 
	 * @param productId
	 * @return
	 */
	@RequestMapping(value = "/get")
	public @ResponseBody ProductDetail get(@RequestParam(value = "productId") long productId) {
		try {
			Product product = baseService.getById(Product.class, productId);
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("product", QueryCondition.EQ, product));
			ProductDetail productDetail = (ProductDetail) baseService.getSingleResult(ProductDetail.class, list);
			return productDetail;
		} catch (Exception e) {
			e.printStackTrace();
			return new ProductDetail();
		}
	}

	/**
	 * 修改某个商品详情
	 * 
	 * @param proudDetail
	 * @return
	 */
	@RequestMapping(value = "/update")
	@ResponseBody
	@RequiresAuthentication
	@RequiresRoles("product-administrator")
	public Object updateProductDetail(long productId, String productDetails) {
		ResponseResult rr = new ResponseResult();
		 Product product = baseService.getById(Product.class, productId);
		 if(product==null){
			 rr.setCode(0);
			 return rr;
		 }
		 
		// 验证 productDetail是否正确。 TODO
		ProductDetail productDetail = baseService.getById(ProductDetail.class, productId);
		if (productDetail == null) {
			productDetail = new ProductDetail();
			productDetail.setId(productId);
			productDetail.setProduct(product);
			productDetail.setImageId(product.getThumbId());
		}
		productDetail.setDetails(productDetails);
		

		try {
			baseService.update(productDetail);

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			return rr;
		}

		rr.setCode(1);
		rr.setInfo("success");
		rr.setObject("");
		return rr;
	}

}
